/**
 * 处理post请求参数
 * @param {string} body
 * @returns {Object}
 */
function param1Obj(body) {
  if (!body) {
    return {};
  }
  const obj = {};
  const searchArr = body.split('&');
  searchArr.forEach(v => {
    const index = v.indexOf('=');
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  let params = decodeURIComponent(obj.params);
  return params;
}
/**
 * 处理get请求url参数
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split('&');
  searchArr.forEach(v => {
    const index = v.indexOf('=');
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone');
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

const validationUtils = (params, validation) => {
  let arr = params.split('&');
  let paramsObj = {};
  arr.forEach(item => {
    let sonArr = item.split('=');
    paramsObj[sonArr[0]] = decodeURIComponent(sonArr[1]);
  });

  if (!validation) {
    // 当validation为undefied，不校验参数
    return {
      isSend: true
    };
  }
  // 找出缺少的参数集合
  let missParams = [];
  missParams =
    Object.keys(validation).filter(key => {
      return !Object.keys(paramsObj).some(key2 => key2 === key);
    }) || [];
  if (missParams.length) {
    return {
      isSend: false,
      msg: '缺少以下参数',
      missParams
    };
  } else {
    let keys = [];

    // 找出必填参数但未传参
    Object.keys(validation).forEach(key => {
      if (validation[key] && !paramsObj[key].toString().length) keys.push(key);
    });
    if (keys.length) {
      return {
        isSend: false,
        msg: `参数${keys.join(',')}为必填项，但其值为undefined`
      };
    } else {
      return {
        isSend: true
      };
    }
  }
};

module.exports = {
  param1Obj,
  param2Obj,
  deepClone,
  validationUtils
};
